package com.example.loginproject.user

import android.content.Context
import com.example.loginproject.tool.MyLog
import com.example.loginproject.file.FileManage
import java.lang.ref.WeakReference

//WeakReference弱引用，A拥有B，B拥有A，要等A销毁时，才能释放B，要等B销毁时才能释放A，所以都不能销毁，成了死锁，
//若用弱引用就能解除这个死锁
class UserManager private constructor(private val context:WeakReference<Context>){
    //存所有的用户对象
    private val users = arrayListOf<User>()
    private val fileManager = FileManage.sharedInstance()
    //静态是全局的，生命周期很长,一直存在,创建单例对象
    companion object{
        private var instance:UserManager? = null
        fun sharedInstance(context:Context): UserManager {
            if(instance == null){
                synchronized(this){
                    if(instance == null){
                        instance = UserManager(WeakReference(context))
                    }
                }
            }
            return instance!!
        }
    }
    //加载所有用户信息
    fun loadAllUserInfo(){
        fileManager.readData(context.get()!!).also{
            users.addAll(it)
            MyLog.v("$users")
        }
    }
    //判断是否有用户
    fun hasUser() = users.size>0
    //用户名是否存在
    fun checkUser(name:String):Boolean{
        users.forEach {
            if (it.name == name){
                return true
            }
        }
        return false
    }
    //判断用户名和密码是否正确
        fun checkUser(name:String,password:String,type:Int):Boolean{
        users.forEach {user->
                if(user.name == name){//找用户
                  return  if(type == PasswordType.LoginType_Pin){
                         user.pin == password
                }else{
                    user.pattern == password
                    }
            }
        }
        return false
    }
    //获取当前登录用户
    fun currentUser():User?{
        //筛选
      users.filter{ it.isLogin}.also {
        return if(it.isNotEmpty()){
              it[0]//同一时间只有一个登录用户
          }else{
              null
          }
      }
    }
    //保存注册用户信息
    fun registUser(name: String,pin:String,pattern: String){
        users.add(User(name,pin, pattern,false))
    }
    //用户登录
    fun login(name:String,password:String,type: Int):Boolean{
        var user: User? = null
        users.forEach{
            if (it.name == name){
                if (type == PasswordType.LoginType_Pin){
                    if(it.pin == password){
                        user = it
                    }
                }else{
                    if (it.pattern == password){
                        user = it
                    }
                }
            }
        }
        return if(user!= null){
            currentUser()?.let { it.isLogin = false }
            user?.isLogin = true
            //将所有信息写入文件
            fileManager.writeData(context.get()!!,users)
            true
        }else{
            false
        }
    }
}